package com.runvp.handler;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.config.RunvpConfig;
import com.runvp.common.constant.ConstantRedisKey;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.core.redis.RedisLockClient;
import com.runvp.common.enums.*;
import com.runvp.common.model.tcp.MessageReceiveBody;
import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.common.utils.DateUtils;
import com.runvp.service.biz.domain.BizDevice;
import com.runvp.service.build.BuildQRCode;
import com.runvp.service.tcp.TcpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Component
public class CmdLoginHandler {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisLockClient lockClient;
    @Autowired
    private TcpService tcpService;
    /**
     * 设备登录逻辑处理
     * @param parseBody
     * @return MessageResBody
     */
    public MessageResBody handle(MessageReceiveBody parseBody){
        log.info("设备登录逻辑处理:::receiveBody:{}",JSONObject.toJSONString(parseBody));
        String batchNo = System.nanoTime()+"";
        String sn = parseBody.getTerminalId();
        tcpService.addBizTcpRecord(parseBody.setBatchNo(batchNo));
        long id = createBizDevice(parseBody);
        MessageResBody resBody = buildRes(id);
        resBody.setBatchNo(batchNo);
        resBody.setTerminalId(sn);
        resBody.setDeviceId(id);
        tcpService.addBizTcpRecord(resBody.setBatchNo(batchNo));
        tcpService.instanceRedisUtil().setCacheObject(ConstantRedisKey.DEVICE_SN_ID+sn,id);
        log.info("设备登录逻辑处理:::resBody:{}",JSONObject.toJSONString(resBody));
        return resBody;
    }

    /**
     * 默认报文
     *
     * @return MessageResBody
     */
    public MessageResBody buildRes(long id) {
        MessageResBody resBody = new MessageResBody(NettyType.SERVER_RECEIVE_DEVICE.getCode(), NettyCmd.LOGIN.getCode());
        resBody.setDid("000000000000");
        resBody.setVersion("01");
        resBody.setBodyJson(buildBody(id)).buildRes();
        return resBody;
    }
    /**
     * 结构结果体
     * @return str
     */
    private JSONObject buildBody(long id){
        JSONObject map = new JSONObject();
        map.put("rs",1);
        map.put("er",0);
        map.put("id",id);
        map.put("pn",10);
        String dateStr = DateUtils.dateTimeNow();
        map.put("yy",dateStr.substring(0,4));
        map.put("mm",dateStr.substring(4,6));
        map.put("dd",dateStr.substring(6,8));
        map.put("hh",dateStr.substring(8,10));
        map.put("ii",dateStr.substring(10,12));
        map.put("ss",dateStr.substring(12,14));
        return map;
    }
    /**
     * 初始化默认数据
     *
     * @return str
     */
    private synchronized long createBizDevice(MessageReceiveBody parseBody) {
        String sn = parseBody.getTerminalId();
        BizDevice query = new BizDevice();
        query.setDeviceCode(sn);
        List<BizDevice> deviceList = tcpService.instanceIBizDeviceService().selectBizDeviceList(query);
        BizDevice device;
        if (CollectionUtils.isEmpty(deviceList)) {
            device = new BizDevice();
            device.setDeviceType(DeviceType.WECHAT.getCode());
            device.setStatus(EnableStatus.DISABLE.getCode());
            device.setStockStatus(YesOrNo.YES.getCode());
            device.setDoorLockStatus(DoorLockStatus.CLOSE.getCode());
            device.setRenewStatus(RenewStatus.NORMAL.getCode());
            device.setDueDtime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, "2100-12-29 23:59:59"));
            device.setCreateTime(DateUtils.getNowDate());
            device.setDeviceCode(sn);
        } else {
            device = deviceList.get(0);
        }
        device.setLastUpdateTime(DateUtils.getNowDate());
        device.setLineStatus(LineStatus.ON_LINE.getCode());
        if (device.getId() == null) {
            tcpService.instanceIBizDeviceService().insertBizDevice(device);
            log.info("设备【{}】执行新增,执行时间:【{}】", sn, DateUtils.now());
        } else {
            device.setUpdateTime(DateUtils.getNowDate());
            device.setQrCode(BuildQRCode.createCode(device.getDeviceCode(), RunvpConfig.getPreview() + "/wechat.html?baseSn=" + device.getDeviceCode()));
            tcpService.instanceIBizDeviceService().updateBizDevice(device);
            log.info("设备【{}】执行修改,执行时间:【{}】", sn, DateUtils.now());
        }
        return device.getId();
    }
}
